package com.haiyou.dc.mq.bi.impl;

import com.haiyou.dc.mq.bi.RabbitMqService;
import com.haiyou.dc.mq.vo.LogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

/**
 * @author pc
 */
@Slf4j
@Service
public class RabbitMqServiceImpl implements RabbitMqService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private Environment env;

    @Override
    public void sendProductMessage(String message) {
        rabbitTemplate.setExchange(env.getProperty("mq.basic.product.exchange"));
        rabbitTemplate.setRoutingKey(env.getProperty("mq.basic.product.routeKey"));
        rabbitTemplate.convertAndSend(message);
    }

    @Override
    public void sendLogMessage(LogVo logVo) {
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange(env.getProperty("mq.log.exchange"));
        rabbitTemplate.setRoutingKey(env.getProperty("mq.log.routeKey"));
        rabbitTemplate.convertAndSend(logVo, message -> {
            log.info("--------------------->发送日志消息={}", logVo);
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_KEY_CLASSID_FIELD_NAME, LogVo.class);
            return message;
        });
    }


}
